<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { handleAlertLogApi, batchHandleAlertLogApi, AlertLogModel } from '@/api/alerts/alertLog';

// Props
const props = defineProps<{
  visible: boolean;
  alertLog: AlertLogModel | null;
  alertLogIds?: number[];
}>();

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'handle-success': [];
}>();

const i18n = useI18n();
const { t } = i18n;

// 判断是否为批量处理模式
const isBatchMode = computed(() => props.alertLogIds && props.alertLogIds.length > 0);

// 表单数据
const formData = ref({
  handleStatus: 2, // 默认标记为已完成
  handRemark: ''
});

// 提交中状态
const loading = ref(false);

// 对话框显示状态（局部状态）
const dialogVisible = ref(props.visible);

// 监听props.visible变化，同步到局部状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
}, { immediate: true });

// 监听告警日志变化，重置表单
watch(() => props.alertLog, (newVal) => {
  if (newVal && !isBatchMode.value) {
    formData.value = {
      handleStatus: newVal.handleStatus || 2,
      handRemark: newVal.handRemark || ''
    };
  }
}, { immediate: true });

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  emit('update:visible', false);
};

// 监听对话框局部状态变化，通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 处理告警
const handleSubmit = async () => {
  loading.value = true;
  try {
    if (isBatchMode.value) {
      // 批量处理
      const response = await batchHandleAlertLogApi(
        props.alertLogIds!,
        formData.value.handleStatus,
        formData.value.handRemark
      );
      
      if (response.code === 0) {
        ElMessage.success(t('alerts.alertLogPage.batchHandleSuccess'));
        emit('handle-success');
        handleClose();
      } else {
        ElMessage.error(response.msg || t('alerts.alertLogPage.batchHandleFailed'));
      }
    } else if (props.alertLog) {
      // 单个处理
      const response = await handleAlertLogApi(
        props.alertLog.id,
        formData.value.handleStatus,
        formData.value.handRemark
      );
      
      if (response.code === 0) {
        ElMessage.success(t('alerts.alertLogPage.handleSuccess'));
        emit('handle-success');
        handleClose();
      } else {
        ElMessage.error(response.msg || t('alerts.alertLogPage.handleFailed'));
      }
    }
  } catch (error) {
    ElMessage.error(isBatchMode.value ? t('alerts.alertLogPage.batchHandleFailed') : t('alerts.alertLogPage.handleFailed'));
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isBatchMode ? t('alerts.alertLogPage.batchHandleDialog.title') : t('alerts.alertLogPage.handleDialog.title')"
    width="400px"
    @close="handleClose"
  >
    <el-form
      :model="formData"
      label-width="100px"
    >
      <el-form-item
        :label="t('alerts.alertLogPage.table.handleStatus')"
        prop="handleStatus"
      >
        <el-select v-model="formData.handleStatus">
          <el-option
            :label="t('alerts.alertLogPage.status.unhandled')"
            :value="0"
          />
          <el-option
            :label="t('alerts.alertLogPage.status.handling')"
            :value="1"
          />
          <el-option
            :label="t('alerts.alertLogPage.status.completed')"
            :value="2"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item
        :label="t('alerts.alertLogPage.table.handRemark')"
        prop="handRemark"
      >
        <el-input
          v-model="formData.handRemark"
          type="textarea"
          :rows="3"
          :placeholder="isBatchMode ? t('alerts.alertLogPage.batchHandleDialog.remarkPlaceholder') : t('alerts.alertLogPage.handleDialog.remarkPlaceholder')"
        />
      </el-form-item>
      
      <!-- 批量处理时显示记录数量 -->
      <div v-if="isBatchMode" class="info-text">
        {{ t('alerts.alertLogPage.batchHandleDialog.recordsCount', { count: alertLogIds.length }) }}
      </div>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">
          {{ t('buttons.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ t('buttons.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.info-text {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
